package com.hegongda.servlet;

import com.hegongda.bean.Orders;
import com.hegongda.bean.PageBean;
import com.hegongda.bean.Product;
import com.hegongda.bean.User;
import com.hegongda.service.AdminService;
import com.hegongda.service.OrderService;
import com.hegongda.utils.BeanFactory;
import net.sf.json.JSONObject;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.*;
@MultipartConfig
@WebServlet(value = "/adminServlet")
public class AdminServlet extends BaseServlet {
    private AdminService as = BeanFactory.newInstance(AdminService.class);
    public void updateClassify(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String cid = request.getParameter("cid");
        String cname = request.getParameter("cname");
        int i = as.updNav(cid,cname);

        if(i != 1){
            Result re = new Result(Result.FAILS, "修改失败，稍后再试！");
            request.setAttribute("errors",re);
        }
        request.getRequestDispatcher("/productServlet?method=getAllNav&admin=admin").forward(request,response);

    }
    public void addClassify(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String cname = request.getParameter("cname");
        int i = as.addNav(cname);
        Result re;
        if(i != 1){
            re = new Result(Result.FAILS, "添加失败，稍后再试！");
            request.setAttribute("errors",re);
        }
        request.getRequestDispatcher("/productServlet?method=getAllNav&admin=admin").forward(request,response);
    }
    public void delClassify(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String cid = request.getParameter("cid");
        int i = as.delNav(cid);
        Result re;
        if(i != 1){
            re = new Result(Result.FAILS, "此分类有商品,无法删除！");
            request.setAttribute("errors",re);
        }
        request.getRequestDispatcher("/productServlet?method=getAllNav&admin=admin").forward(request,response);

    }
    public void allProduct(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String pagenum = request.getParameter("pagenum");
        if("null".equals(pagenum)||"".equals(pagenum)||pagenum==null){
            pagenum = "1";
        }
        PageBean<Product> pageProduct = as.getPageProduct(Constr.PAGESIZE-4,Integer.valueOf(pagenum));
        request.setAttribute("pb",pageProduct);
        request.getRequestDispatcher("/view/admin/product/list.jsp").forward(request,response);
    }
    public void delProduct(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String pid = request.getParameter("pid");
        int i = as.delPriduct(pid,this.getServletContext().getRealPath("/"));
        Result re;
        if(i == 1) {
            re = new Result(Result.SUCCESS, "删除成功");
        }else {
            re = new Result(Result.FAILS, "此商品存在订单,无法删除！");
        }
        response.getWriter().print(JSONObject.fromObject(re));
    }

    public void addProductI(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String content1 = request.getParameter("content1");
        String iid = request.getParameter("iid");
        if(content1!=null&&!"".equals(content1)) {
            as.addintroduce(iid, content1);
        }
        allProduct(request,response);
    }

    public void addProduct(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        Map<String, String[]> map = request.getParameterMap();
        Collection<Part> parts = request.getParts();
        String path = this.getServletContext().getRealPath("/");
        Part part = request.getPart("upload");//上传文件对象的描述
        //System.out.println(part.getName());
        String h = part.getHeader("content-disposition");
        // h是要上传的文件的头：具体如下（上传桌面上的account.txt文件）
        // form-data; name="fileName"; filename="C:\Users\ASUS\Desktop\account.txt"
        //把传上来的account.txt文件命名为"newFile"保存在服务器中
        String fname = UUID.randomUUID().toString().replace("-","");
        String pid = fname;
        //substring是在获取文件的后缀，改名但是不改后缀
        fname = fname + h.substring(h.lastIndexOf("."), h.length() - 1);
        String str = "resources\\products\\1\\"+fname;
        //按照路径上传文件(修改path可以改变文件在服务器中的存储位置）
        part.write(path + str);
        Product product = new Product();
        try {
            BeanUtils.populate(product,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        product.setPid(pid);
        String iid = UUID.randomUUID().toString().replace("-","");
        product.setIid(iid);
        product.setPimage("resources/products/1/"+fname);
        product.setPdate(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        int i = as.addPriduct(product);
        request.setAttribute("iid",iid);
        request.getRequestDispatcher("/view/admin/product/demo.jsp").forward(request,response);
    }

    public void updPFlag(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        int pflag = Integer.parseInt(request.getParameter("pflag"));
        String pid = request.getParameter("pid");
        int i = as.updPFlag(pflag, pid);
        if(i != 1){
            Result re = new Result(Result.FAILS, "修改失败，稍后再试！");
            request.setAttribute("errors",re);
        }
        allProduct(request,response);
    }
    public void allUser(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String pagenum = request.getParameter("pagenum");
        if("null".equals(pagenum)||"".equals(pagenum)||pagenum==null){
            pagenum = "1";
        }
        PageBean<User> pageProduct = as.getPageUser(Constr.PAGESIZE-4,Integer.valueOf(pagenum));
        request.setAttribute("adminuser",pageProduct);
        request.getRequestDispatcher("/view/admin/user/list.jsp").forward(request,response);
    }
    public void delUser(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String uid = request.getParameter("uid");
        int i = as.delUser(uid);
        Result re;
        if(i != 1){
            re = new Result(Result.FAILS, "用户存在订单,无法删除！");
            request.setAttribute("errors",re);
        }
        allUser(request,response);

    }


    public void updateUser(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        Map<String, String[]> usermap = request.getParameterMap();
        User user = new User();
        try {
            BeanUtils.populate(user,usermap);
        } catch (Exception e) {
        }
        System.out.println(user);
        int i = as.updUser(user);

        if(i != 1){
            Result re = new Result(Result.FAILS, "修改失败，稍后再试！");
            request.setAttribute("errors",re);
        }
        allUser(request,response);

    }
    public void getOneUser(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String uid = request.getParameter("uid");
        User oneUser = as.getOneUser(uid);
        request.setAttribute("user",oneUser);
        request.getRequestDispatcher("/view/admin/user/edit.jsp").forward(request,response);
    }

    public void selAllOrder(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String pagenum = request.getParameter("pagenum");
        if(pagenum==null){
            pagenum="1";
        }
        PageBean<Orders> allOrder = as.selAllOrder(2, Integer.parseInt(pagenum));
        request.setAttribute("pb",allOrder);
        request.getRequestDispatcher("/view/admin/order/list.jsp").forward(request,response);
    }

    public void editCourierNum(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String oid = request.getParameter("oid");
        String couriernum = request.getParameter("couriernum");
        int i = as.editCourierNum(oid, couriernum);
        selAllOrder(request, response);
    }

    public void editCourier(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String oid = request.getParameter("oid");
        String couriernum = request.getParameter("couriernum");
        int i = as.editCourierNum(oid, couriernum);
        selAllOrder(request, response);
    }

    public void recoveryOrder(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String oid = request.getParameter("oid");
        OrderService os = BeanFactory.newInstance(OrderService.class);
        os.updateOrderState(oid, Constr.ORDER_YIWANC);
        selAllOrder(request, response);
    }
}
